package controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import dao.Check_OutDao;
import dao.impl.Check_OutDaoImpl;
import entity.Check;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@WebServlet(urlPatterns = "/check_OutController")
public class Check_OutController extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req,resp);
    }
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setCharacterEncoding("utf-8");
        req.setCharacterEncoding("utf-8");
        String op = req.getParameter("op");
        PrintWriter out = resp.getWriter();
        
        if ("tscx".equals(op)){
            String operator = req.getParameter("operator");
            int page = Integer.parseInt(req.getParameter("page") == null ? "1" : req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("pageSize") == null ? "5" : req.getParameter("pageSize"));
            
            // 确保页码有效
            if (page < 1) page = 1;
            
            Check_OutDao dao = new Check_OutDaoImpl();
            List<Check> list = null;
            int totalCount = 0;
            try {
                list = dao.show(operator, page, pageSize);
                totalCount = dao.getTotalCount(operator);
                
                // 计算总页数
                int totalPages = (int) Math.ceil((double)totalCount / pageSize);
                
                // 构造返回JSON对象
                Map<String, Object> result = new HashMap<>();
                result.put("list", list);
                result.put("page", page);
                result.put("pageSize", pageSize);
                result.put("totalPages", totalPages);
                result.put("totalCount", totalCount);
                
                out.write(JSON.toJSONString(result));
            } catch (Exception e) {
                e.printStackTrace();
                out.write(JSON.toJSONString(new HashMap<String, Object>() {{
                    put("error", e.getMessage());
                }}));
            }
        }
    }
}
